#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests


def uploadFile(file_path,webdav_url,webdav_user,webdav_pass, target_filename=None):
    # 上传文件 到webdav
    headers = { 'Content-Type': 'application/octet-stream'            }
    try:
        # 构建目标URL，如果提供了目标文件名则使用，否则使用原文件名
        import os
        if target_filename:
            # 确保URL以/结尾
            if not webdav_url.endswith('/'):
                webdav_url += '/'
            webdav_url = webdav_url + target_filename
        with open(file_path, 'rb') as f:
            response = requests.put(
                webdav_url,
                auth=(webdav_user, webdav_pass),
                headers=headers,
                data=f,
                timeout=300  # 5分钟超时
            )
            
            # 检查上传结果
            if 200 <= response.status_code < 300:
                return ({
                    'success': True,
                    'message': '文件上传成功',
                })
            else:
                return {
                    'success': False,
                    'message': f'WebDAV服务器错误: {response.status_code} - {response.reason}'
                }
    except Exception as e:
        return {
            'success': False,
            'message': f'上传文件时发生错误: {str(e)}'
        }


if __name__ == '__main__':
    file="c:/adb.png"
    url="http://alist.polarxrobotics.com:5050/webdav/sqlBack"
    t=uploadFile(file,url,"admin","CHFShu0303","a.png")
    print(t)